<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>AI 智能问答</title>
    <style>
        .chat-container {
            width: 60%;
            margin: 60px auto;
            border: 1px solid #ccc;
            padding: 15px;
            border-radius: 10px;
            background: #f9f9f9;
        }
        #chatHistory {
            height: 400px;
            overflow-y: auto;
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
        .input-area {
            display: flex;
            padding-top: 10px;
        }
        .input-area input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        .input-area button {
            margin-left: 10px;
            padding: 10px;
            border: none;
            background: #007bff;
            color: white;
            border-radius: 5px;
            cursor: pointer;
        }
        .message-container {
            display: flex;
            align-items: center;
            margin: 10px 0;
        }
        .message-container img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
        }
        .user-message, .ai-message {
            max-width: 60%;
            padding: 10px;
            border-radius: 10px;
            word-wrap: break-word;
        }
        .user-message {
            background: #007bff;
            color: white;
            align-self: flex-end;
        }
        .ai-message {
            background: #e1e1e1;
            color: black;
        }
    </style>
</head>
<body>

<%
    String defaultUrl = "https://tse1-mm.cn.bing.net/th/id/OIP-C.j57souiFOvYA0LUiw-2BkAHaHa?rs=1&pid=ImgDetMain";
    HttpSession session1 = request.getSession();
    String userType = (String) session1.getAttribute("userType");
    String avatarUrl = null;

    if (userType != null) {
        if ("admin".equals(userType)) {
            avatarUrl = (String) session1.getAttribute("adminAvatarUrl");
        } else {
            avatarUrl = (String) session1.getAttribute("avatarUrl");
        }
    }
    String userAvatarImgPath = (avatarUrl != null && !avatarUrl.isEmpty()) ? avatarUrl : defaultUrl;
    String AiImgPath = "./images/Ai.jpg"; // AI 头像路径
%>
<div class="chat-container">
    <div id="chatHistory"></div>
    <div class="input-area">
        <input type="text" id="userInput" placeholder="请输入您的问题...">
        <button onclick="sendMessage()">发送</button>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    const userAvatarImgPath = '<%= userAvatarImgPath %>';
    const AiImgPath = '<%= AiImgPath %>';

    function sendMessage() {
        const userInput = document.getElementById('userInput');
        const message = userInput.value.trim();
        if (!message) return;

        appendMessage('user', message, userAvatarImgPath);
        userInput.value = '';

        fetch('sparkServlet', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'message=' + encodeURIComponent(message)
        })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    appendMessage('ai', data.message, AiImgPath);
                } else {
                    appendMessage('ai', '错误：' + data.message, AiImgPath);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                appendMessage('ai', '发生错误，请稍后重试', AiImgPath);
            });
    }

    function appendMessage(type, message, avatar) {
        const chatHistory = document.getElementById('chatHistory');
        const messageContainer = document.createElement('div');
        messageContainer.className = "message-container";

        const avatarImg = document.createElement('img');
        avatarImg.src = avatar;
        avatarImg.alt = type === 'user' ? '用户' : 'AI';

        const messageDiv = document.createElement('div');
        messageDiv.className = type + '-message';
        messageDiv.textContent = message;

        if (type === 'user') {
            messageContainer.style.justifyContent = "flex-end";
            messageContainer.appendChild(messageDiv);
            messageContainer.appendChild(avatarImg);
        } else {
            messageContainer.appendChild(avatarImg);
            messageContainer.appendChild(messageDiv);
        }

        chatHistory.appendChild(messageContainer);
        chatHistory.scrollTop = chatHistory.scrollHeight;
    }

    document.getElementById('userInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
</script>

</body>
</html>
